package com.woniuxy.education.controller;

import com.woniuxy.education.entity.Perm;
import com.woniuxy.education.entity.User;
import com.woniuxy.education.service.UserService;
import com.woniuxy.education.utils.ResponseResult;
import com.woniuxy.education.utils.UpPhotoNameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    private static final Logger logger= LoggerFactory.getLogger(UserController.class);
    private static final String UPLOAD_PATH ="D://uploadimages//" ;
    @Autowired
    UserService userService;
    @RequestMapping("/login")
    public  ResponseResult login(User user){
        ResponseResult responseResult=new ResponseResult();
        User user1=userService.findUserByAccont(user.getAccount());
        if(user1==null){
            responseResult.setCode(400);
            responseResult.setMessage("账号或者密码错误");
            return  responseResult;
        }
        if(user.getPassword().equals(user1.getPassword())){
            if(user1.getType_id()==0){
                System.out.println(user1.getId());
                user1.setStudent(userService.findStudent(user1.getId()));
            }
            List<Perm> listAllPerms=userService.queryAllMenu(user1.getId());
            responseResult.setData(user1);
            responseResult.setRights(listAllPerms);
            responseResult.setCode(200);
            return  responseResult;
        }else {
            responseResult.setCode(400);
            responseResult.setMessage("账号或者密码错误");
            return  responseResult;
        }

    }
    //查询用户所有信息
    @RequestMapping("/findData")
    public  ResponseResult findData(int userid, int type_id){
        ResponseResult responseResult=new ResponseResult();
        if(type_id == 0){
            responseResult.setData(userService.findStudent(userid));
            responseResult.setCode(200);
            return  responseResult;
          }
        responseResult.setCode(400);
        return  responseResult;
    }

    @RequestMapping("/uploadPhotos")
    public  String singleFileUpload(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file){
        try {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            System.out.println(file);
            String fileName = UpPhotoNameUtils.getPhotoName("img",imageFileName);
            Path path = Paths.get(UPLOAD_PATH + fileName);
            Files.write(path, bytes);
            System.out.println(fileName+"\n");
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    //使用流将图片输出
    @GetMapping("/getImage/{name}")
    public void getImage(HttpServletResponse response, @PathVariable("name") String name) throws IOException {
        response.setContentType("image/jpeg;charset=utf-8");
        response.setHeader("Content-Disposition", "inline; filename=girls.png");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(Files.readAllBytes(Paths.get(UPLOAD_PATH).resolve(name)));
        outputStream.flush();
        outputStream.close();
    }

    //将头像地址写入数据库
    @GetMapping("/changephone")
    public ResponseResult changephone(int id,int type_id,String head_picture) {
        ResponseResult responseResult = new ResponseResult();
        if(userService.changephone(id,type_id,head_picture)){
          responseResult.setCode(200);
          responseResult.setMessage("修改成功");
          return responseResult;
        }else {
            responseResult.setCode(400);
            responseResult.setMessage("修改失败");
            return  responseResult;
        }
    }
}
//
//System.out.println(user);
//        //1.获取到""当前用户""对象
//        Subject currentUser= SecurityUtils.getSubject();
//        //获取session
//        Session session = currentUser.getSession();
//        //在表示,DAO,service中都可以用
//        //调用方法获得  SecurityUtils.getSubject().getSession().getAttribute("name");
////        session.setAttribute("name","lisi");
//        ResponseResult responseResult=new ResponseResult();
//        //2.判断用户是否认证过
//        if (!currentUser.isAuthenticated()){
//
//        String password=new SimpleHash("MD5",user.getPassword()).toString();
//        //没有认证过  token 令牌
//        UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(),password);
//
//        //判断用户是否勾选记住我
//        if(user.isRm()){
//        token.setRememberMe(true);//使用记住我的功能
//        }
//        //当前用户携带令牌去认证,去找securitymanager
//        //认证时可能会报异常,只要出现异常说明令牌有问题
//        //不报异常说明账号密码没问题
//        try {
//        //登录这里只会调用用户验证的方法,不会调用查询权限的方法
//        currentUser.login(token);
//        logger.info("认证成功");
//        responseResult.setCode(200);
//        responseResult.setRights(SecurityUtils.getSubject().getSession().getAttribute("userperms"));
//        responseResult.setData(SecurityUtils.getSubject().getSession().getAttribute("user"));
//        return responseResult;
//        }catch (UnknownAccountException e){
//        //账号不存在
//        responseResult.setMessage("账号不存在");
//        return responseResult;
//        }
//        catch (IncorrectCredentialsException e){
//        e.printStackTrace();
//        //密码错误
//        return responseResult;
//        }
//        }
//        return responseResult;